package wqh.shui_ya.modbus;

import cn.tpson.modbus.core.ModBusDevice;
import cn.tpson.modbus.core.ModBusManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import wqh.domain.WaterChannel;
import wqh.domain.WaterDevice;
import wqh.global.GlobalTime;
import wqh.global.GlobalWaterChannel;
import wqh.service.WaterChannelService;
import wqh.service.WaterDeviceService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.sql.DriverManager;
import java.util.List;


/**
 * Created by devts on 2016/12/15.
 */
@WebServlet(name = "WaterServlet")
public class WaterModbusServlet extends HttpServlet {

    @Override
    public void destroy() {
        super.destroy();
        ModBusManager.getInstance().release();
        try {
            DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("水压解析启动#####################################");
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:/spring/spring-data.xml","classpath:/spring/spring-beans.xml");
        WaterDataCallBack waterDataCallBack = (WaterDataCallBack)ac.getBean("waterDataCallBack");
        ModBusManager.getInstance().setCallBack(waterDataCallBack);
        WaterDeviceService waterDeviceService = (WaterDeviceService) ac.getBean("waterDeviceService");
        List<WaterDevice> waterDevices = waterDeviceService.findAll();
        if(waterDevices.size() != 0){
            for(WaterDevice w : waterDevices){
                ModBusDevice modBusDevice = new ModBusDevice(w.getIp(),w.getPort(), GlobalTime.seconds);
                modBusDevice.setAddress((byte)1);
                ModBusManager.getInstance().addDevice(modBusDevice);
            }
        }
        WaterChannelService waterChannelService = (WaterChannelService) ac.getBean("waterChannelService");
        List<WaterChannel> waterChannels = waterChannelService.findAll();
        if(waterChannels.size() != 0){
            for(WaterChannel w : waterChannels){
                GlobalWaterChannel.addDevice(w.getWaterDevice().getIp() + ":" + w.getWaterDevice().getPort() + "H" + w.getChannel_number(),w.getHigh());
                GlobalWaterChannel.addDevice(w.getWaterDevice().getIp() + ":" + w.getWaterDevice().getPort() + "L" + w.getChannel_number(),w.getLow());
            }
        }
    }
}
